import os
import re
import logging

# 设置日志文件路径
root_path = os.path.dirname(os.path.realpath(__file__))
log_file = os.path.join(root_path, f'log.txt')
# 配置日志（带初始时间戳）
file_handler = logging.FileHandler(log_file, encoding='utf-8')
file_handler.setFormatter(logging.Formatter('%(asctime)s\n%(message)s'))
logging.basicConfig(level=logging.INFO, handlers=[file_handler])
logging.info("=== 脚本启动 ===")
# 移除时间戳格式
file_handler.setFormatter(logging.Formatter('%(message)s'))

def debug_print(msg):
    print(msg)
    logging.info(msg)

def extract_mac(line: str) -> str:
    """专用MAC地址提取函数"""
    # 步骤1：查找固定前缀
    prefix = "2: MAC地址           OK  ["
    start_idx = line.find(prefix)
    if start_idx == -1:
        debug_print(f"!! 前缀匹配失败 | 前缀: {prefix}")
        return None
    
    # 步骤2：计算mac起始位置
    mac_start = start_idx + len(prefix)
    debug_print(f"  前缀长度: {len(prefix)}, MAC起始位置: {mac_start}")

    # 步骤3：查找第一个]
    end_idx = line.find(']', mac_start)
    if end_idx == -1:
        debug_print("!! 未找到结束符]")
        return None

    # 提取并清洗数据
    mac = line[mac_start:end_idx].strip().upper()
    debug_print(f"  原始MAC字符串: '{line[mac_start:end_idx]}'")
    return mac

try:
    with open('xxx.txt', 'r', encoding='gb2312') as f:
        content = f.read()
        debug_print(f"文件读取成功，长度: {len(content)}字符")
except UnicodeDecodeError as e:
    print(f"!! 文件编码错误: {str(e)}")
    exit()

# 分割测试记录
records = [r.strip() for r in content.split('-----------------------------------------------------------------------') if r.strip()]
debug_print(f"发现 {len(records)} 条测试记录")

sql_statements = []
for idx, record in enumerate(records, 1):
    debug_print(f"\n====== 正在处理第{idx}条记录 ======")
    ts = mac = v_100 = v_950 = ld = None

    for line in record.split('\n'):
        line = line.strip()
        debug_print(f"当前行: {line}")

        # 提取测试时间
        if line.startswith('测试时间:'):
            ts = line.split('测试时间:')[1].strip()
            debug_print(f"  解析到测试时间: {ts}")

        # 调用专用MAC解析函数
        elif 'MAC地址' in line:
            debug_print("-- 进入MAC地址解析流程 --")
            mac = extract_mac(line)
            debug_print(f"  最终MAC地址: {mac}")

        # 高压100V测试值
        elif '高压输出100V测试' in line and 'OK' in line:
            parts = line.split()
            v_100 = parts[-1].rstrip('V')
            debug_print(f"  解析到100V电压: {v_100}V")

        # 高压950V测试值 
        elif '高压输出950V测试' in line and 'OK' in line:
            parts = line.split()
            v_950 = parts[-1].rstrip('V')
            debug_print(f"  解析到950V电压: {v_950}V")

        # 漏电流测试值
        elif '电池漏电流测试' in line and 'OK' in line:
            parts = line.split()
            ld = parts[-1].rstrip('mA')
            debug_print(f"  解析到漏电流: {ld}mA")

    # 完整性检查
    debug_print("\n记录解析结果:")
    debug_print(f"  ts: {ts} | mac: {mac} | v_100: {v_100} | v_950: {v_950} | ld: {ld}")

    if all([ts, mac, v_100, v_950, ld]):
        sql = f"""UPDATE [dbo].[T_GBTCCS2BoardTest]
 SET [ck_hivolout_100_bool] = 1
      ,[ck_hivolout_100] = {v_100}
      ,[ck_hivolout_950_bool] = 1
      ,[ck_hivolout_950] = {v_950}
      ,[ck_bat_leak] = {ld}
      ,[ck_bat_leak_bool] = 1
 WHERE [mac] = '{mac}' AND [ts] = '{ts}';"""
        sql_statements.append(sql)
        debug_print("√ SQL生成成功")
    else:
        debug_print("!! 数据不完整，跳过本记录")

# 结果输出
debug_print(f"\n共生成 {len(sql_statements)} 条有效SQL")
with open('sql.txt', 'w', encoding='utf-8') as f:
    f.write('\n'.join(sql_statements))
    debug_print(f"结果已写入sql.txt")